package com.ulook.lookplanet.util.net;

import com.ulook.lookplanet.common.AppServer;
import com.ulook.lookplanet.util.ThrowException;
import com.ulook.lookplanet.util.json.ResponseParser;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 描述：同步请求线程
 *
 * @author: L1998
 * @data: 2021/3/24
 */
public class SynRequestThread extends Thread{

    private int method;                    //请求方式
    private String url;                    //地址
    private RequestParams params;          //参数
    private Response response;             //响应对象
    private OkHttpClient okHttpClient;
    private boolean success;               //响应结果
    private String data;                   //响应数据

    public SynRequestThread(String url, RequestParams params){
        this.url = url;
        this.params = params;
        okHttpClient = CommonOkHttpClient.getmOkHttpClient();
        success = false;
    }

    public void startToGet(){
        this.method = AppServer.GET;
        this.start();
    }

    public void startToPost() {
        this.method = AppServer.POST;
        this.start();
    }

    @Override
    public void run() {

        Request request = null;
        if(method == AppServer.POST){
            request = CommonRequest.createPostRequest(url, params);
        }else if(method == AppServer.GET){
            request = CommonRequest.createGetRequest(url, params);
        }
        //开始进行同步请求
        try {
            response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful()){
                String code = ResponseParser.parserCode(response);
                if("0".equals(code)){
                    success = true;
                    data = ResponseParser.parserData(response);
                }
            }else{
                response = null;
                success = false;
            }
        } catch (IOException e) {
            response = null;
            success = false;
            ThrowException.print(e, Thread.currentThread().getName(), "同步请求失败");
        }
    }

    public boolean isSuccess() {
        return success;
    }

    public String getData() {
        return data;
    }
}
